package com.yeheng.controller;


import com.yeheng.dto.Condition;
import com.yeheng.dto.Result;
import com.yeheng.entity.Emp;
import com.yeheng.service.EmpService;
import com.yeheng.validationgroup.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

/**
 * @Classname EmpController
 * @Description :
 * @Date 2020/12/26 12:57
 * @Created by Yeheng
 */
@Controller
@RequestMapping("/emp")
public class EmpController {

    @Autowired
    EmpService service;

    @RequestMapping(value = "/findAll", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Result findEmp(@RequestBody Condition cond) {
        Result result = new Result();
        result.setResult(service.findAll(cond));
        result.setCode(0);
        result.setMsg("");
        result.setCount(service.count(cond));
        return result;
    }

    @RequestMapping(value = "/findByEid", method = RequestMethod.POST)
    @ResponseBody
    public Result findByEid(Integer eid) {
        Result result = new Result();
        result.setResult(service.findByEid(eid));
        result.setCode(0);
        result.setMsg("");
        return result;
    }

    @RequestMapping(value = "/delByEid", method = RequestMethod.POST)
    @ResponseBody
    public Result delByEid(Integer eid) {
        Result result = new Result();
        result.setResult(null);
        result.setCode(service.delByEid(eid) == true ? 0 : -1);
        result.setMsg("");
        result.setCount(0);
        return result;
    }

    @RequestMapping(value = "/updateEmp", method = RequestMethod.POST)
    @ResponseBody
    public Result updateEmp(@RequestBody Emp emp) {
        System.out.println(emp);
        Result result = new Result();
        result.setResult(null);
        result.setCode(service.updateEmp(emp) == true ? 0 : -1);
        result.setMsg("");
        result.setCount(null);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/addEmp", method = RequestMethod.POST)
    public Result addEmp(@RequestBody @Validated Emp emp, Errors errors) {

        Result result = new Result();
        result.setResult(null);
        if (errors.hasErrors()) {
            result.setMsg(errors.getFieldErrors().get(0).getDefaultMessage());
            System.out.println(errors.getFieldErrors().get(0).getDefaultMessage());
        } else {
            result.setCode(service.addEmp(emp) == true ? 0 : -1);
            result.setMsg("");
        }
        result.setCount(null);
        return result;
    }
}
